/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.bme.j2ee.v37zen.beans;

import hu.bme.j2ee.v37zen.entities.User;
import hu.bme.j2ee.v37zen.util.Role;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Kiss Dániel
 */
@Stateless
@LocalBean
@RolesAllowed("ADMIN")
public class AdministratorBean {

    @PersistenceContext
    EntityManager em;
    @EJB
    FindUsersBean fub;

    /**
     * Creates a new instance of AdminManagedBean
     */
    public AdministratorBean() {
        
    }
    
    public void promoteUserToAdmin(String user){
        em.flush();
        this.promoteUserToAdmin(fub.findUserByUsername(user));
    }
    
    public void promoteUserToAdmin(User user){
        if(user == null){
            return;
        }
        user = em.merge(user);
        user.getRoles().size();
        user.setRoles(Role.SET_of_USDER_AND_ADMIN);
        user.setRole_a_JAAS_miatt(Role.ADMIN);
        em.flush();
    }
    
    public void disrateAdminToUser(String user){
        em.flush();
        this.disrateAdminToUser(fub.findUserByUsername(user));
    }
    
    public void disrateAdminToUser(User user){
        if(user == null){
            return;
        }
        user = em.merge(user);
        user.getRoles().size();
        user.setRoles(Role.SET_of_USER_ONLY);
        user.setRole_a_JAAS_miatt(Role.USER);
        em.flush();
    }
    
    public void removeUser(String user){
        em.flush();
        this.removeUser(fub.findUserByUsername(user));
    }
    
    public void removeUser(User user){
        if(user == null){
            return;
        }
        user = em.merge(user);
        em.flush();
        em.remove(user);        
    }
    
    public List<User> getUpToDateUserList(){
        em.flush();
        return fub.findAllUser();
    }
}
